import 'package:base_lib/app.dart';
import 'package:base_lib/common/base/base_bloc_page.dart';
import 'package:base_lib/common/widget/peach_button.dart';
import 'package:base_lib/index.dart';
import 'package:base_lib/router/parameters.dart';
import 'package:base_lib/theme/theme_global.dart';
import 'package:base_lib/utils/gap.dart';
import 'package:base_lib/utils/screen_adapter.dart';
import 'package:base_lib/utils/shared_preference_util.dart';
import 'package:base_lib/utils/util.dart';
import 'package:doctor_login_lib/component.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:fsuper/fsuper.dart';
import 'bloc.dart';

class LoginPage extends BaseBlocPage<LoginBloc, _LoginState> {
  LoginPage(Parameters parameters) : super(parameters);

  @override
  _LoginState generateThemeState() {
    return _LoginState();
  }
}

class _LoginState extends BaseBlocPageState<LoginBloc>
    with SingleTickerProviderStateMixin {
  TapGestureRecognizer userAgreementRecognizer = TapGestureRecognizer();
  TapGestureRecognizer privacyAgreementRecognizer = TapGestureRecognizer();

  TextEditingController tecPhone = TextEditingController();
  TextEditingController tecPwd = TextEditingController();

  void initState() {
    super.initState();
    userAgreementRecognizer.onTap = () {
      Utils.jump2WebView(context, "桃子云门诊注册协议",
          App.PATH_REMOTE_H5 + "/person/agreementRegister.html");
    };
    privacyAgreementRecognizer.onTap = () {
      Utils.jump2WebView(context, "法律声明及隐私权政策",
          App.PATH_REMOTE_H5 + "/person/statementRegister.html");
    };
    SPUtil.remove('token');
    SPUtil.remove('phone');
    SPUtil.remove('pwd');
  }

  @override
  ignoreWindowWidget() => false;

  @override
  Widget buildChild(BuildContext context, MTheme theme) {
    return Scaffold(
      body: Container(
        color: Colors.white,
        height: double.infinity,
        child: LayoutBuilder(
          builder: (context, cons) {
            var w400;
            return Container(
              margin: EdgeInsets.only(top: 60),
              constraints: cons,
              padding: EdgeInsets.symmetric(horizontal: 28),
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      "登录",
                      style: TextStyle(
                          color: Colors.black,
                          fontWeight: FontWeight.w500,
                          fontSize: 30),
                    ),
                    StreamBuilder(
                        initialData: false,
                        stream: bloc.useCodeLogin,
                        builder: (context, AsyncSnapshot<bool> useCodeLogin) {
                          return Padding(
                            padding: const EdgeInsets.only(top: 70.0),
                            child: _selectLoginTypeViewBuilder(
                                theme, useCodeLogin.data),
                          );
                        }),
                    Container(
                        margin: EdgeInsets.only(top: 10.0),
                        width: double.infinity,
                        child: _buildPhone(theme)),
                    StreamBuilder(
                      initialData: false,
                      stream: bloc.useCodeLogin,
                      builder: (context, AsyncSnapshot<bool> useCodeLogin) {
                        return Container(
                          width: ScreenAdapter.screenWidthDp,
                          child: Container(
                            child: useCodeLogin.data
                                ? _buildSmsCode(theme)
                                : _buildPwd(theme),
                          ),
                        );
                      },
                    ),
                    _registerAndPasswordViewBuilder(theme),
                    10.vGapDp,
                    _loginButtonBuilder(theme),
                    Center(
                      child: Container(
                        margin: EdgeInsets.only(top: 30),
                        child: _agreement(theme),
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  // 注册&忘记密码按钮
  Widget _registerAndPasswordViewBuilder(MTheme theme) {
    return StreamBuilder(
        initialData: false,
        stream: bloc.useCodeLogin,
        builder: (context, AsyncSnapshot<bool> useCodeLogin) {
          return Container(
            margin: EdgeInsets.only(top: 10),
            height: 40,
            child: Row(
              children: [
                GestureDetector(
                  onTap: () {
                    bloc.jump2Register(context);
                  },
                  child: Text(
                    "注册",
                    style: TextStyle(color: theme.themeColor.themeColor),
                  ),
                ),
                Spacer(),
                GestureDetector(
                  onTap: () {
                    bloc.jump2ForgotPassword(context);
                  },
                  child: Text(
                    "忘记密码?",
                    style: TextStyle(color: Colors.grey),
                  ),
                )
              ],
            ),
          );
        });
  }

  // 登录按钮
  Widget _loginButtonBuilder(MTheme theme) {
    return StreamBuilder(
        stream: bloc.loadingStatus,
        initialData: false,
        builder: (context, AsyncSnapshot<bool> loading) {
          return StreamBuilder(
            initialData: false,
            stream: bloc.useCodeLogin,
            builder: (context, AsyncSnapshot<bool> codeLogin) {
              return Padding(
                padding: const EdgeInsets.only(top: 15.0),
                child: peachButtonBuilder(
                    onTap: () {
                      Utils.hideSoftKeyboard(context);
                      if (!loading.data) {
                        if (codeLogin.data)
                          bloc.loginByCode(context);
                        else
                          bloc.login(context);
                      }
                    },
                    text: loading.data ? "请求中..." : '登录'),
              );
            },
          );
        });
  }

  // 选择登录方式操作
  Widget _selectLoginTypeViewBuilder(MTheme theme, bool isCodeLogin) {
    return Row(children: [
      Expanded(
          child: FlatButton(
        splashColor: Colors.transparent,
        highlightColor: Colors.transparent,
        child: Text("手机验证码登录",
            style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w400,
                color: isCodeLogin
                    ? theme.themeColor.themeColor
                    : theme.themeColor.themeLightGreyColor)),
        onPressed: isCodeLogin
            ? null
            : () {
                bloc.changeLoginType();
              },
      )),
      Expanded(
          child: FlatButton(
        splashColor: Colors.transparent,
        highlightColor: Colors.transparent,
        child: Text(
          "账号密码登录",
          style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w400,
              color: isCodeLogin
                  ? theme.themeColor.themeLightGreyColor
                  : theme.themeColor.themeColor),
        ),
        onPressed: isCodeLogin
            ? () {
                bloc.changeLoginType();
              }
            : null,
      )),
    ]);
  }

  ///手机号输入框
  Widget _buildPhone(MTheme theme) {
    return StreamBuilder(
      stream: bloc.historyPhone,
      builder: (context, snapshot) {
        return Column(
          children: [
            TextField(
                keyboardType: TextInputType.phone,
                maxLength: 11,
                onChanged: (value) {
                  bloc.editPhoneChanged(value);
                },
                controller: tecPhone..value.copyWith(text: snapshot.data),
                strutStyle: StrutStyle(
                    fontSize: theme.themeFontSize.fontSizeBig, height: 1),
                style: TextStyle(
                    color: Colors.black,
                    fontSize: theme.themeFontSize.fontSizeBig),
                decoration: InputDecoration(
                  hintText: "请输入您的手机号",
                  counterText: "",
                  hintStyle: TextStyle(
                      color: theme.themeColor.themeLightGreyColor,
                      fontSize: 18),
                  border: InputBorder.none,
                )),
            Divider(
              height: 10,
              color: theme.themeColor.themeLightGreyColor,
            )
          ],
        );
      },
    );
  }

  ///密码输入框
  Widget _buildPwd(MTheme theme) {
    return Stack(
      children: [
        StreamBuilder(
          stream: bloc.historyPwd,
          builder: (context, snapshot) {
            return Column(
              children: [
                StreamBuilder(
                    initialData: true,
                    stream: bloc.passObscureSubject,
                    builder: (context, AsyncSnapshot<bool> obscureText) {
                      return TextField(
                          keyboardType: TextInputType.visiblePassword,
                          obscureText: obscureText.data,
                          maxLength: 20,
                          onChanged: (value) {
                            bloc.editPwdChanged(value);
                          },
                          controller: tecPwd
                            ..value.copyWith(text: snapshot.data),
                          strutStyle: StrutStyle(
                              fontSize: theme.themeFontSize.fontSizeBig,
                              height: 1),
                          style: TextStyle(
                              color: Colors.black,
                              fontSize: theme.themeFontSize.fontSizeBig),
                          decoration: InputDecoration(
                            hintText: "请输入您的密码",
                            counterText: "",
                            hintStyle: TextStyle(
                                color: theme.themeColor.themeLightGreyColor,
                                fontSize: 18),
                            border: InputBorder.none,
                          ));
                    }),
                Divider(
                  height: 10,
                  color: theme.themeColor.themeLightGreyColor,
                )
              ],
            );
          },
        ),
        Positioned(
            right: 0,
            top: 16,
            child: StreamBuilder(
                initialData: true,
                stream: bloc.passObscureSubject,
                builder: (context, AsyncSnapshot<bool> obscureText) {
                  return GestureDetector(
                    onTap: () async {
                      bloc.passwordObscureSubType();
                    },
                    child: Image.asset(
                      obscureText.data
                          ? "images/eye-off.png"
                          : "images/eye-on.png",
                      height: 15,
                      width: 15,
                      package: DoctorLoginComponent.AssetsPackageName,
                    ),
                  );
                }))
      ],
    );
  }

  ///验证码输入框
  Widget _buildSmsCode(MTheme theme) {
    return Stack(children: <Widget>[
      Column(
        children: [
          TextField(
            onChanged: (value) {
              bloc.smsCodeChanged(value);
            },
            keyboardType: TextInputType.number,
            maxLength: 20,
            strutStyle: StrutStyle(
                fontSize: theme.themeFontSize.fontSizeBig, height: 1),
            style: TextStyle(
                color: Colors.black, fontSize: theme.themeFontSize.fontSizeBig),
            decoration: InputDecoration(
              hintText: "请输入验证码",
              counterText: "",
              hintStyle: TextStyle(
                  color: theme.themeColor.themeLightGreyColor, fontSize: 18),
              border: InputBorder.none,
            ),
          ),
          Divider(
            height: 10,
            color: theme.themeColor.themeLightGreyColor,
          )
        ],
      ),
      Positioned(
          right: 0,
          top: 12,
          child: StreamBuilder<int>(
              initialData: 0,
              stream: bloc.sentSmsCount.stream,
              builder: (context, snapshot) {
                return GestureDetector(
                    onTap: () async {
                      bloc.sentSms();
                    },
                    child: Container(
                      child: Padding(
                        padding: const EdgeInsets.only(
                            top: 3.0, left: 8.0, bottom: 3.0, right: 8.0),
                        child: Text(
                          snapshot.data == 0 ? "获取验证码" : "${snapshot.data}s",
                          style: TextStyle(
                              color: snapshot.data == 0
                                  ? theme.themeColor.themeColor
                                  : Colors.grey,
                              fontSize: theme.themeFontSize.fontSizeNormal),
                        ),
                      ),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(14.0)),
                          border: Border.all(
                              width: 1, color: theme.themeColor.themeColor)),
                    ));
              }))
    ]);
  }

  ///隐私协议部分
  Widget _agreement(MTheme theme) {
    return Column(children: [
      Text("登录即代表您已阅读并同意以下协议",
          style: TextStyle(
              color: theme.themeColor.themeLightGreyColor,
              fontSize: theme.themeFontSize.fontSizeSmall)),
      5.vGapDp,
      Row(
        children: [
          Expanded(
            child: Container(
              alignment: Alignment.center,
              child: GestureDetector(
                onTap: userAgreementRecognizer.onTap,
                child: Text("《桃子云门诊注册协议》",
                    style: TextStyle(
                        color: theme.themeColor.themeColor,
                        fontSize: theme.themeFontSize.fontSizeLittle)),
              ),
            ),
          ),
          Expanded(
            child: Container(
              alignment: Alignment.center,
              child: GestureDetector(
                onTap: privacyAgreementRecognizer.onTap,
                child: Text("《法律声明及隐私权政策》",
                    style: TextStyle(
                        color: theme.themeColor.themeColor,
                        fontSize: theme.themeFontSize.fontSizeLittle)),
              ),
            ),
          )
        ],
      ),
    ]);
  }

  @override
  LoginBloc generateBloc() {
    var bb = LoginBloc();
    return bb;
  }
}
